// src/pages/room/widgets/action/index.tsx
import styles from "@styles/room.module.scss";
import { PictureOutline } from "antd-mobile-icons";
import { OrderStatus } from "@enums/consult";
import {useState} from "react";
import {Toast} from "antd-mobile";
import {useUploadMutation} from "@store/apiSlice/uploadApiSlice";

interface Props {
    // 订单状态
    status: OrderStatus;
    sendMsg: (text: string) => void;
    sendImage: (image: Image) => void;
}

export default function Action({ status,sendMsg,sendImage }: Props) {
    // 用于记录用户在文本框中输入的内容
    const [text, setText] = useState("");
    // 用于发送消息
    const checkIsEnter = (event: React.KeyboardEvent<HTMLInputElement>)=>{
        //检测用户是否敲击了回车键
        if (event.key === "Enter"){
            sendMsg(text);
            setText("")
        }
    }
    // 用于文件上传
    const [upload] = useUploadMutation();
    // 用于上传图片
    const onFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        // 获取文件列表
        const files = event.currentTarget.files;
        // 判断文件列表是否为空
        if (files === null) return;
        // 获取文件
        const file = files[0];
        // 判断文件是否小于5M
        if (file.size / 1024 / 1024 > 5) return Toast.show({ content: "图片不能大于5M" });
        // 创建 formData 对象
        const formData = new FormData();
        // 向 formData 对象中追加图片
        formData.append("file", file);
        // 上传图片
        upload(formData)
            .unwrap()
            .then((response) => {
                // 发送图片
                sendImage(response.data);
            });
    };
    return (
        <div className={styles.bottom}>
            <input
                disabled={status !== OrderStatus.ConsultChat}
                type="text"
                className={styles.ask}
                placeholder="问医生"
                value={text}
                onChange={(event) => setText(event.target.value)}
                onKeyUp={checkIsEnter}
            />
            <div className={styles.upload}>
                <PictureOutline />
                <input type="file" disabled={status !== OrderStatus.ConsultChat}  accept="image/*"   onChange={onFileChange}/>
            </div>
        </div>
    );
}